package com.justgame.project.cloud.common.query;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.google.common.base.CaseFormat;
import com.justgame.project.cloud.common.util.MyBatisUtils;
import org.springframework.stereotype.Component;

@Component
public class QueryNamingHandler implements Query.QueryHandler {
    @Override
    public void handle(Query query) {
        String tableName = MyBatisUtils.getAnnotationTableName(query.getCurrentTableClass());
        if (query.getCurrentTableSelectColumns().length == 1 && StringPool.ASTERISK.equals(query.getCurrentTableSelectColumns()[0])){
            query.setCurrentTableSelectColumns(MyBatisUtils.tableClassFieldNames(query.getCurrentTableClass()).toArray(new String[0]));
        }
        String[] newColumnArr = new String[query.getCurrentTableSelectColumns().length];
        for (int i = 0; i < query.getCurrentTableSelectColumns().length; i++) {
            String col = query.getCurrentTableSelectColumns()[i];
            newColumnArr[i] = MyBatisUtils.buildSelectAlias(
                    tableName,
                    CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE,col),
                    query.getAliasPrefix(),
                    col);
        }
        query.setCurrentTableSelectColumns(newColumnArr);
    }

    @Override
    public int sort() {
        return Integer.MAX_VALUE;
    }
}
